﻿using FileTransfer.Assistantor;
using FileTransfer.Vollk.Model;
using HAF.FtpUtility;
using HAF.FtpUtility.Enum;
using HAF.FtpUtility.Model;
using HAF.LogUtility;
using HAF.LogUtility.Except;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace FileTransfer.Vollk
{
    /// <summary>
    /// M3U8文件下载处理
    /// </summary>
    public class M3u8TaskAssistant
    {
        M3u8TaskModel _runTask;
        string taskUrl = string.Empty;
        SiteTaskConfig _siteConfig;
        List<TsEntity> runSubTasks = new List<TsEntity>();

        #region 构造函数
        /// <summary>
        /// m3u8文件地址
        /// </summary>
        /// <param name="m3u8Url"></param>
        public M3u8TaskAssistant(M3u8TaskModel task)
        {
            _runTask = task;
            taskUrl = task.M3u8Path;
            _siteConfig = FtpUrlParser.ParseFtpUrl(_runTask.M3u8Url);
        }
        
        /// <summary>
        /// m3u8-ts集合
        /// </summary>
        /// <param name="tsTasks"></param>
        public M3u8TaskAssistant(List<TsEntity> tsTasks)
        {
            runSubTasks = tsTasks;
        }
        #endregion 构造函数

        public void DownParts()
        {
            if (!string.IsNullOrEmpty(taskUrl))
            {
                GetM3u8Content(taskUrl);
            }
            
            //如果存在待处理集合
            if (runSubTasks != null && runSubTasks.Count > 0)
            {
                foreach (var item in runSubTasks)
                {
                    LogHelper.WriteDebugLogExt(_runTask.TaskID, "开始下载M3u8文件{0}列表中的{1}", taskUrl, item.UrlRemote);
                    using (FluentFtpHelper ftpClient = new FluentFtpHelper(_siteConfig))
                    {
                        ftpClient.LogOutName = _runTask.TaskID;
                        //ftpClient.DownloadMessageEvent = WriteConsolMessageEvent;
                        //ftpClient.DownloadProcessChangeEvent = WriteProcessEvnet;
                        //ftpClient.DownloadChangeEvent = DownloadChangeEvent;
                        ftpClient.DownFile(item.UrlLocal, item.UrlRemote);
                    }
                    Thread.Sleep(12000);
                }
            }
        }

        private void GetM3u8Content(string url)
        {
            LogHelper.WriteDebugLogExt(_runTask.TaskID, "加载本地M3U8文件{0}", url);
            string m3u8Content = FileAssistanter.ReadAllText(url);
            if (!string.IsNullOrEmpty(m3u8Content))
            {
                //文件有效性判断
                if (m3u8Content.ToLower().StartsWith("#EXTM3U".ToLower()))
                {
                    foreach (string line in m3u8Content.Split('\n'))
                    {
                        if (line.Trim().ToLower().EndsWith(".TS".ToLower()))
                        {
                            runSubTasks.Add(new TsEntity()
                            {
                                //ftp://zzx_tencent_m3u8:zzx123456@182.138.25.61/20240511/n41009qwd1q.2.n41009qwd1q.321004/n41009qwd1q.2.n41009qwd1q.321004.ts.m3u8
                                UrlRemote = string.Format("{0}/{1}", _siteConfig.RemotePath, line.TrimEnd('\r')),
                                UrlLocal = Path.Combine(_runTask.LocalDirectory, line.TrimEnd('\r')),
                                Status = 0
                            });
                        }
                    }
                }
                else
                {
                    throw new RunException(TransferCode.FileCheckErr, "非标准M3U8文件格式");
                }
            }

        }
    }
}
